import org.junit.Test;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

/**
 * @author Jimmy Zhan WORKSTATION
 * @date 2023/3/31 10:54
 * 说明：
 */

public class URLDownloadTest {
    @Test
    public void test1() {
        HttpURLConnection urlConnection = null;
        InputStream is = null;
        FileOutputStream fos = null;
        try {
            // 1. 获取url的实例
            URL url = new URL("http://127.0.0.1:8080/examples/abcd.jpg");
            // 2. 建立与服务器端的连接
            urlConnection = (HttpURLConnection)url.openConnection();
            // 3. 获取输入流、创建输出流
            is = urlConnection.getInputStream();
            File file = new File("dest.jpg");
            fos = new FileOutputStream(file);

            // 4. 读写数据
            byte[] buffer = new byte[1024];
            int len;
            while ((len = is.read(buffer)) != -1){
                fos.write(buffer, 0, len);
            }
            System.out.println("Complete");
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            // 5. 关闭资源
            try {
                if (fos != null) {
                    fos.close();
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            try {
                if (is != null) {
                    is.close();
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            if (urlConnection != null) {
                urlConnection.disconnect();
            }
        }

    }
}
